package top.lixunda.ecommerce.server.auth.service.impl;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lixunda.ecommerce.server.auth.entity.SmsResult;
import top.lixunda.ecommerce.server.auth.properties.SmsProperties;
import top.lixunda.ecommerce.server.auth.service.ISmsService;
import top.lixunda.ecommerce.server.auth.utils.HttpUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 发送短信验证码Service
 *
 * @author Xumda
 * @deprecated 2019年12月17日14:32:44
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    private static final String OPERATION = "/industrySMS/sendSMS";

    private final SmsProperties smsProperties;

    private final HttpUtil httpUtil;

    private static final SmsResult DEFAULT_ERROR_RESULT = new SmsResult();

    @Autowired
    public SmsServiceImpl(SmsProperties smsProperties, HttpUtil httpUtil) {
        this.smsProperties = smsProperties;
        this.httpUtil = httpUtil;
        DEFAULT_ERROR_RESULT.setRespCode("9999");
        DEFAULT_ERROR_RESULT.setRespDesc("无返回结果");
    }

    /**
     * 发送短信验证码
     *
     * @param code   随机生成的短信验证码
     * @param to     发送的手机号码
     * @param aimStr 发送的内容模板，已经通过常量自定义
     * @return 返回自定义的数据结构，将验证的手机号码与发送的验证码进行绑定
     */
    @Override
    public SmsResult sendSmsCode(String code, String to, final String aimStr) {
        String url = smsProperties.getBaseUrl() + OPERATION;
        String body = "accountSid=" + smsProperties.getSid() + "&to=" + to + "&templateid=" +
                aimStr + "&param=" + code + "," + "5" + createCommonParam();
        //提交请求
        String result = httpUtil.post(url, body);
        if (result == null) {
            return DEFAULT_ERROR_RESULT;
        }
        log.debug("sms code={} to={} aimStr={} result={}", code, aimStr, to, result);
        Gson gson = new Gson();
        return gson.fromJson(result, SmsResult.class);
    }

    /**
     * 构造通用的参数timestamp. sig和respDataType;
     *
     * @return 返回构造好的参数字符串
     */
    private String createCommonParam() {
        //时间戳
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA).format(new Date());
        //签名
        String sig = DigestUtils.md5Hex(smsProperties.getSid() + smsProperties.getToken() + timestamp);
        return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType=" + smsProperties.getDataType();
    }
}
